package com.subject.shuati.domain.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.subject.shuati.common.enums.IsDeleteFlagEnum;
import com.subject.shuati.domain.covert.SubjectCategoryConverter;
import com.subject.shuati.domain.entity.SubjectCategoryBo;
import com.subject.shuati.domain.entity.SubjectLabelBo;
import com.subject.shuati.domain.service.SubjectCategoryDomainService;
import com.subject.shuati.domain.utils.CacheUtil;
import com.subject.shuati.infra.basic.entity.SubjectCategory;
import com.subject.shuati.infra.basic.entity.SubjectLabel;
import com.subject.shuati.infra.basic.entity.SubjectMapping;
import com.subject.shuati.infra.basic.service.SubjectCategoryService;
import com.subject.shuati.infra.basic.service.SubjectLabelService;
import com.subject.shuati.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {

    @Resource
    private SubjectCategoryService subjectCategoryService;

    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private ThreadPoolExecutor labelThreadPool;
    @Resource
    private CacheUtil cacheUtil;
    @Override
    public void addSubject(SubjectCategoryBo subjectCategoryBo) {
        if (log.isInfoEnabled()){
            log.info("SubjectCategoryController.add.Bo:{}", JSON.toJSONString(subjectCategoryBo));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.Instance.covertToCategory(subjectCategoryBo);
        subjectCategory.setIsDeleted(IsDeleteFlagEnum.UN_DELETE.code);
        subjectCategoryService.insert(subjectCategory);
    }

    @Override
    public Boolean update(SubjectCategoryBo subjectCategoryBo) {
        if (log.isInfoEnabled()){
            log.info("SubjectCategoryController.update.Bo:{}", JSON.toJSONString(subjectCategoryBo));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.Instance.covertToCategory(subjectCategoryBo);
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @Override
    public Boolean delete(SubjectCategoryBo subjectCategoryBo) {
        if (log.isInfoEnabled()){
            log.info("SubjectCategoryController.delete.Bo:{}", JSON.toJSONString(subjectCategoryBo));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.Instance.covertToCategory(subjectCategoryBo);
        subjectCategory.setIsDeleted(IsDeleteFlagEnum.DELETE.getCode());
        int count = subjectCategoryService.update(subjectCategory);
        return count > 0;
    }

    @Override
    public List<SubjectCategoryBo> queryCategory(SubjectCategoryBo subjectCategoryBo) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.Instance.covertToCategory(subjectCategoryBo);
        subjectCategory.setIsDeleted(IsDeleteFlagEnum.UN_DELETE.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBo> boList = SubjectCategoryConverter.Instance
                .covertToCategoryBoList(subjectCategoryList);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryPrimaryCategory.boList:{}",
                    JSON.toJSONString(boList));
        }
        boList.forEach(bo -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(subjectCount);
        });
        return boList;
    }

    @SneakyThrows
    @Override
    public List<SubjectCategoryBo> queryCategoryAndLabel(SubjectCategoryBo subjectCategoryBo) {
        Long id = subjectCategoryBo.getId();
        String cacheKey = "categoryAndLabel"+ subjectCategoryBo.getId();
        List<SubjectCategoryBo> subjectCategoryBoList =
                cacheUtil.getResult(cacheKey, SubjectCategoryBo.class, (key) -> getSubjectCategoryBos(id));
        return subjectCategoryBoList;

    }

    private List<SubjectCategoryBo> getSubjectCategoryBos(Long categoryId) {
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeleteFlagEnum.UN_DELETE.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryCategoryAndLabel.subjectCategoryList:{}",
                    JSON.toJSONString(subjectCategoryList));
        }
        List<SubjectCategoryBo> categoryBOList = SubjectCategoryConverter.Instance.covertToCategoryBoList(subjectCategoryList);
        Map<Long, List<SubjectLabelBo>> map = new HashMap<>();
        List<CompletableFuture<Map<Long, List<SubjectLabelBo>>>> completableFutureList = categoryBOList.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getLabelBoList(category), labelThreadPool)
        ).collect(Collectors.toList());
        completableFutureList.forEach(future -> {
            try {
                Map<Long, List<SubjectLabelBo>> resultMap = future.get();
                if (!MapUtils.isEmpty(resultMap)) {
                    map.putAll(resultMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        categoryBOList.forEach(categoryBO -> {
            if (!CollectionUtils.isEmpty(map.get(categoryBO.getId()))) {
                categoryBO.setLabelBOList(map.get(categoryBO.getId()));
            }
        });
        return categoryBOList;
    }

    private Map<Long, List<SubjectLabelBo>> getLabelBoList(SubjectCategoryBo subjectCategoryBo) {
        if (log.isInfoEnabled()) {
            log.info("getLabelBOList:{}", JSON.toJSONString(subjectCategoryBo));
        }
        Map<Long, List<SubjectLabelBo>> labelMap = new HashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setCategoryId(subjectCategoryBo.getId());
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelByCategoryId(subjectMapping);
        if (CollectionUtils.isEmpty(subjectMappingList)){
            return null;
        }
        List<Long> labelIdList = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> subjectLabels = subjectLabelService.queryBatchByLabelIds(labelIdList);
        List<SubjectLabelBo> labelBoList = new LinkedList<>();
        subjectLabels.forEach(subjectLabel -> {
            SubjectLabelBo labelBo = new SubjectLabelBo();
            labelBo.setId(subjectLabel.getId());
            labelBo.setLabelName(subjectLabel.getLabelName());
            labelBo.setSortNum(subjectLabel.getSortNum());
            labelBo.setCategoryId(subjectLabel.getCategoryId());
            labelBoList.add(labelBo);
        });
        labelMap.put(subjectCategoryBo.getId(), labelBoList);
        return labelMap;
    }
}
